package com.leyou.trade.service.impl;

import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    private final CartRepository cartRepository;

    private final MongoTemplate mongoTemplate;

    public CartServiceImpl(CartRepository cartRepository, MongoTemplate mongoTemplate) {
        this.cartRepository = cartRepository;
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void saveCartItem(CartItem cartItem) {
        // 用户信息
        Long userId = UserContext.getUser().getId();

        // 购物车商品信息
        String id = createId(cartItem.getSkuId());
        Optional<CartItem> optional = cartRepository.findById(id);

        // 判断商品信息是否一致
        if (optional.isPresent()) {
            // 记录新商品数量
            Integer num = cartItem.getNum();
            // 获取旧数据
            cartItem = optional.get();
            // 增加数量
            cartItem.setNum(num + cartItem.getNum());
        }

        // 填写id, userId, 时间
        cartItem.setId(id);
        cartItem.setUserId(userId);
        cartItem.setUpdateTime(new Date());

        cartRepository.save(cartItem);

    }

    @Override
    public List<CartItem> queryCartList() {
        Long id = UserContext.getUser().getId();
        return cartRepository.findByUserId(id, Sort.by("updateTime").descending());
    }

    @Override
    public void updateNum(Long skuId, Integer num) {
        mongoTemplate.update(CartItem.class)
                .matching(Query.query(Criteria.where(("_id")).is(skuId)))
                .apply(Update.update("num", num).currentDate("updateTime"))
                .first();
    }

    @Override
    public void deleteCart(Long skuId) {
        cartRepository.deleteById(createId(skuId));
    }

    @Override
    public void addCartItemList(List<CartItem> itemList) {
        Long userId = UserContext.getUser().getId();
        List<CartItem> list =  itemList.stream().map(item -> handleUpdateItem(userId, item)).collect(Collectors.toList());
        cartRepository.saveAll(list);
    }

    private String createId(Long skuId) {
        return String.format("u%ds%d", UserContext.getUser().getId(), skuId);
    }

    private CartItem handleUpdateItem(Long userId, CartItem item) {
        Optional<CartItem> optional = cartRepository.findById(createId(item.getSkuId()));
        if (optional.isPresent()) {
            Integer num = item.getNum();
            CartItem cartItem = optional.get();
            cartItem.setNum(num + cartItem.getNum());
        }

        item.setUserId(userId);
        item.setUpdateTime(new Date());

        return item;
    }
}
